import { getToken, ResponseCode, ResponseStatus, type ResponseBody } from '@/utils'
import type { Method } from 'alova'
import { useUserStore } from '@/store'

/**
 * @description 请求拦截
 */
export const beforeRequest = (method: Method) => {
  if (!method.meta?.ignoreToken) {
    const token = getToken()

    if (!token) {
      window.$message.error('登录已过期，请重新登录！')
      useUserStore().logout()
      return Promise.reject({ status: ResponseStatus.UNAUTHORIZED, message: '登录已过期，请重新登录！' })
    }

    method.config.headers.Authorization = method.config.headers.Authorization || token
  }
}

/**
 * @description 响应成功拦截
 */
export const onSuccess = async (response: Response, method: Method) => {
  if (response.status !== ResponseStatus.SUCCESS) {
    if (response.status === ResponseStatus.UNAUTHORIZED) {
      window.$message.error('登录已过期，请重新登录！')
      useUserStore().logout()
      return Promise.reject(response)
    }

    window.$message.error('请求错误：' + (response.statusText || response.status))
    return Promise.reject(response)
  }

  const responseType: XMLHttpRequestResponseType = method.config.headers?.responseType || 'json'
  if (responseType === 'arraybuffer') {
    return await response.arrayBuffer()
  }

  if (responseType === 'blob') {
    return await response.blob()
  }

  const resJSON = (await response.json()) as ResponseBody<TRecord<any>>

  if (resJSON.code !== ResponseCode.SUCCESS) {
    window.$message.error(resJSON.msg)
    return Promise.reject({ code: resJSON.code, message: resJSON.msg })
  }

  return resJSON
}

/**
 * @description 响应错误拦截
 */
export const onError = (error: Error) => {
  window.$message.error(error.message || '请求失败')
  throw error
}
